var ws = require("nodejs-websocket")
var port=9000;
var user=0;

// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
console.log("New connection");
user++;
conn.nickname="user"+user;
var mes={};
mes.type="enter";
mes.data=conn.nickname+" comes in"
broadcast(JSON.stringify(mes));
conn.on("text", function (str) {
    console.log("Received "+str)
//conn.sendText(str.toUpperCase()+"!!!") var mes={};
    mes.type="message";
    mes.data=conn.nickname+" says: "+str;
    broadcast(JSON.stringify(mes));
})
conn.on("close", function (code, reason) {
    console.log("Connection closed");
    var mes={};
    mes.type="leave";
    mes.data=conn.nickname+" left"
    broadcast(JSON.stringify(mes));
})
conn.on("error", function (err) {
    console.log("handdle error");
    console.log(err);
})
}).listen(port);
console.log("websocket server listening on port "+port);
function broadcast(str){
    server.connections.forEach(function(connection){
        connection.sendText(str);
    })
}
